package com.atguigu.controller;

import com.atguigu.entity.Admin;
import com.atguigu.entity.Permission;
import com.atguigu.entity.Role;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import com.atguigu.service.RoleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author 王健
 * @version 1.0
 */
@Controller
public class IndexController {

    @DubboReference
    private AdminService adminService;

    @DubboReference
    private RoleService roleService;

    @DubboReference
    private PermissionService permissionService;


/*    @RequestMapping("/")
    public String toIndex() {
        return "frame/index";
    }*/

    @RequestMapping("/main")
    public String toMain() {
        return "frame/main";
    }

    /**
     * 添加了SpringSecurity之后去首页的方法
     * @return
     */
    @RequestMapping("/login")
    public String login(){
        return "frame/login";
    }

    @GetMapping("/")
    public String index(ModelMap model) {
        /*
        //后续替换为当前登录用户id
        Long adminId = 11L;//(自己表中的adminId为8、11、13、14的都有权限管理和二手房管理)
        */

        //有SpringSecurity获取当前登录的用户
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //从user中获取账号根据username查询到admin

        //1.查询出当前登录的用户信息存储到请求域
        //Admin admin = adminService.getById(adminId);

        Admin admin = adminService.getByUsername(user.getUsername());
        model.addAttribute("admin", admin);
        //2.查询当前爱登录的用户角色列表存储到请求域
        List<Role> roleList = roleService.findByAdminId(admin.getId());
        model.addAttribute("roleList", roleList);
        //3.查询出当前登录的用户的动态菜单存储到请求域
        List<Permission> permissionList = permissionService.findMenuPermissionByAdminId(admin.getId());
        model.addAttribute("permissionList",permissionList);

        return "frame/index";
    }

    @GetMapping("/auth")
    public String auth() {
        return "frame/auth";
    }
}
